import React, { useState } from 'react'
import { Layout, Menu, Card, Row, Col, Button, Space, Switch, message, Spin } from 'antd'
import { DashboardOutlined, BarChartOutlined, LineChartOutlined, PieChartOutlined, SettingOutlined, UserOutlined, PictureOutlined } from '@ant-design/icons'
import Chart from './components/Chart'
import ImageAnalysisPage from './components/CozeImageAnalyzer/ImageAnalysisPage'
import { useAppStore } from './store'
import { dashboardAPI } from './api/services'
import './App.less'

const { Header, Sider, Content } = Layout

const App: React.FC = () => {
  const [collapsed, setCollapsed] = useState<boolean>(false)
  const [selectedChart, setSelectedChart] = useState<'bar' | 'line' | 'pie'>('bar')
  const [currentPage, setCurrentPage] = useState<'dashboard' | 'image-analysis'>('dashboard')
  const { user, theme, loading, chartData, setTheme, setLoading, setChartData } = useAppStore()

  // 获取图表数据
  const fetchData = async () => {
    setLoading(true)
    try {
      // 调用API获取图表数据
      const response = await dashboardAPI.getChartData({
        type: selectedChart,
        dateRange: undefined,
        category: undefined,
      })

      // 转换API响应数据格式
      const chartData = {
        sales: response.series[0]?.data || [
          Math.random() * 200 + 50,
          Math.random() * 200 + 50,
          Math.random() * 200 + 50,
          Math.random() * 200 + 50,
          Math.random() * 200 + 50,
          Math.random() * 200 + 50,
          Math.random() * 200 + 50,
        ],
        categories: response.categories || ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
      }

      setChartData(chartData)
      message.success('数据更新成功')
    } catch (error) {
      console.error('获取图表数据失败:', error)
      // 如果API调用失败，使用模拟数据
      const mockData = {
        sales: [
          Math.random() * 200 + 50,
          Math.random() * 200 + 50,
          Math.random() * 200 + 50,
          Math.random() * 200 + 50,
          Math.random() * 200 + 50,
          Math.random() * 200 + 50,
          Math.random() * 200 + 50,
        ],
        categories: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
      }
      setChartData(mockData)
      message.warning('使用模拟数据，请检查API连接')
    } finally {
      setLoading(false)
    }
  }

  const menuItems: Array<{
    key: string
    icon: React.ReactNode
    label: string
    onClick?: () => void
  }> = [
    {
      key: '1',
      icon: <PictureOutlined />,
      label: '图片分析',
      onClick: () => setCurrentPage('image-analysis'),
    },
    {
      key: '2',
      icon: <DashboardOutlined />,
      label: '仪表盘',
      onClick: () => setCurrentPage('dashboard'),
    },
    {
      key: '3',
      icon: <BarChartOutlined />,
      label: '柱状图',
      onClick: () => {
        setCurrentPage('dashboard');
        setSelectedChart('bar');
      },
    },
    {
      key: '4',
      icon: <LineChartOutlined />,
      label: '折线图',
      onClick: () => {
        setCurrentPage('dashboard');
        setSelectedChart('line');
      },
    },
    {
      key: '5',
      icon: <PieChartOutlined />,
      label: '饼图',
      onClick: () => {
        setCurrentPage('dashboard');
        setSelectedChart('pie');
      },
    },
    {
      key: '6',
      icon: <SettingOutlined />,
      label: '设置',
    },
  ]

  const getChartTitle = (): string => {
    switch (selectedChart) {
      case 'bar':
        return '销售数据 - 柱状图'
      case 'line':
        return '销售趋势 - 折线图'
      case 'pie':
        return '销售占比 - 饼图'
      default:
        return '数据统计'
    }
  }

  return (
    <Layout style={{ minHeight: '100vh' }}>
      <Sider collapsible collapsed={collapsed} onCollapse={setCollapsed} theme={theme === 'dark' ? 'dark' : 'light'}>
        <div
          className="logo"
          style={{
            height: 32,
            margin: 16,
            background: 'rgba(255, 255, 255, 0.3)',
            borderRadius: 6,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            color: theme === 'dark' ? '#fff' : '#000',
            fontWeight: 'bold',
          }}
        >
          {collapsed ? 'LS' : '大屏展示'}
        </div>
        <Menu 
          theme={theme === 'dark' ? 'dark' : 'light'} 
          defaultSelectedKeys={['1']} 
          mode="inline"
        >
          {menuItems.map(item => (
            <Menu.Item key={item.key} icon={item.icon} onClick={item.onClick}>
              {item.label}
            </Menu.Item>
          ))}
        </Menu>
      </Sider>

      <Layout>
        <Header
          style={{
            padding: '0 16px',
            background: '#fff',
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
          }}
        >
          <h2 style={{ margin: 0 }}>大屏数据展示系统</h2>
          <Space>
            <UserOutlined />
            <span>欢迎，{user.name}</span>
            <Switch
              checkedChildren="🌙"
              unCheckedChildren="☀️"
              checked={theme === 'dark'}
              onChange={checked => setTheme(checked ? 'dark' : 'light')}
            />
          </Space>
        </Header>

        <Content style={{ margin: '16px' }}>
          {currentPage === 'dashboard' ? (
            <Spin spinning={loading}>
              <Row gutter={[16, 16]}>
                <Col span={24}>
                  <Card
                    title="数据概览"
                    extra={
                      <Space>
                        <Button type="primary" onClick={fetchData}>
                          刷新数据
                        </Button>
                      </Space>
                    }
                  >
                    <Row gutter={[16, 16]}>
                      <Col xs={24} sm={12} md={6}>
                        <Card size="small">
                          <div style={{ textAlign: 'center' }}>
                            <div
                              style={{
                                fontSize: 24,
                                fontWeight: 'bold',
                                color: '#1890ff',
                              }}
                            >
                              {chartData.sales.reduce((a, b) => a + b, 0).toFixed(0)}
                            </div>
                            <div>总销售额</div>
                          </div>
                        </Card>
                      </Col>
                      <Col xs={24} sm={12} md={6}>
                        <Card size="small">
                          <div style={{ textAlign: 'center' }}>
                            <div
                              style={{
                                fontSize: 24,
                                fontWeight: 'bold',
                                color: '#52c41a',
                              }}
                            >
                              {Math.max(...chartData.sales).toFixed(0)}
                            </div>
                            <div>最高销售</div>
                          </div>
                        </Card>
                      </Col>
                      <Col xs={24} sm={12} md={6}>
                        <Card size="small">
                          <div style={{ textAlign: 'center' }}>
                            <div
                              style={{
                                fontSize: 24,
                                fontWeight: 'bold',
                                color: '#faad14',
                              }}
                            >
                              {(chartData.sales.reduce((a, b) => a + b, 0) / chartData.sales.length).toFixed(0)}
                            </div>
                            <div>平均销售</div>
                          </div>
                        </Card>
                      </Col>
                      <Col xs={24} sm={12} md={6}>
                        <Card size="small">
                          <div style={{ textAlign: 'center' }}>
                            <div
                              style={{
                                fontSize: 24,
                                fontWeight: 'bold',
                                color: '#f5222d',
                              }}
                            >
                              {chartData.sales.length}
                            </div>
                            <div>数据点数</div>
                          </div>
                        </Card>
                      </Col>
                    </Row>
                  </Card>
                </Col>

                <Col span={24}>
                  <Card title={getChartTitle()}>
                    <Chart type={selectedChart} title={getChartTitle()} />
                  </Card>
                </Col>
              </Row>
            </Spin>
          ) : currentPage === 'image-analysis' ? (
            <ImageAnalysisPage />
          ) : null}
        </Content>
      </Layout>
    </Layout>
  )
}

export default App
